package icu.lookyousmileface.netty.simple

import io.netty.bootstrap.Bootstrap
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelInitializer
import io.netty.channel.EventLoopGroup
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioSocketChannel


/**
 * @title: NettyClient
 * @projectName NettyPro
 * @author shenj
 * @date 2020/12/4 1:38
 */
fun main() {
    val host = "127.0.0.1"
    val port = 7788

    val nioEventLoopGroup:EventLoopGroup = NioEventLoopGroup()
    try {

    //客户端使用Bootstrap
    val startClientApplicationConfiguration = Bootstrap()
    //客户端只需要channel handler
    startClientApplicationConfiguration.group(nioEventLoopGroup)
            .channel(NioSocketChannel::class.java)
            .handler(object : ChannelInitializer<io.netty.channel.socket.SocketChannel>() {
                override fun initChannel(ch: io.netty.channel.socket.SocketChannel?) {
                   ch?.pipeline()?.addLast(NettyClientHandler())
                }
            })

    println("Client is OK!!!")

    val channelFuture : ChannelFuture = startClientApplicationConfiguration.connect(host, port).sync()

    channelFuture.channel().closeFuture().sync()
    }finally {

        nioEventLoopGroup.shutdownGracefully()
    }
}